# -*- coding:utf-8 -*-
# =================================
# File : rapedetect0523.py
# Create Time : 2024/5/23 9:12
# Author : chenxu
# Description : 
# =================================
# -*- coding:utf-8 -*-
# =================================
# File : dahengdetect_saveimg.py
# Create Time : 2024/4/24 16:26
# Author : chenxu
# Description :
# =================================
import cv2
import numpy as np
import time
import gxipy as gx

device_manager = gx.DeviceManager()
dev_num, dev_info_list = device_manager.update_device_list()
if dev_num == 0:
    print("Number of enumerated devices is 0")
#     return

# open the first device
cam = device_manager.open_device_by_index(1)

cam.TriggerMode.set(gx.GxSwitchEntry.OFF)
# set exposure
cam.ExposureTime.set(1800.0)  # 曝光时间：20~1000000us
# cam.BalanceRatioSelector.set(0)# 白平衡通道：0,Red;1,Green;2,Blue;
cam.BalanceWhiteAuto.set(2)  # 自动白平衡模式：0,off；1,Continuous；2,Once
# 自动增益
cam.GainAuto.set(1)  # 0,关闭；1，连续；2，单次；

# get param of improving image quality
if cam.GammaParam.is_readable():
    gamma_value = cam.GammaParam.get()
    gamma_lut = gx.Utility.get_gamma_lut(gamma_value)
else:
    gamma_lut = None
if cam.ContrastParam.is_readable():
    contrast_value = cam.ContrastParam.get()
    contrast_lut = gx.Utility.get_contrast_lut(contrast_value)
else:
    contrast_lut = None
if cam.ColorCorrectionParam.is_readable():
    color_correction_param = cam.ColorCorrectionParam.get()
else:
    color_correction_param = 0

# start data acquisition
cam.stream_on()
time0 = time.strftime("%Y-%m-%d-%H-%M-%S")

tttt = 1
while True:
    time.sleep(0.1)
    # # 屏蔽前20帧图像
    # if count <= 20:
    #     count += 1
    #     continue
    # 从第 0 个流通道获取一幅图像
    raw_image = cam.data_stream[0].get_image()  # 使用相机采集一张图片
    if raw_image is None:
        continue
    # 从彩色原始图像获取 RGB 图像
    rgb_image = raw_image.convert("RGB")  # 从彩色原始图像获取 RGB 图像
    if rgb_image is None:
        continue
    # 实现图像质量提升
    # rgb_image.image_improvement(color_correction_param, contrast_lut, gamma_lut)
    numpy_image = rgb_image.get_numpy_array()  # 从 RGB 图像数据创建 numpy 数组
    if numpy_image is None:
        continue
    frame = cv2.cvtColor(numpy_image, cv2.COLOR_RGB2BGR)
    # 增加图像裁剪
    # 大恒旧相机MER-132-43U3C裁剪参数
    # xmin, ymin, w, h = 300, 200, 800, 600
    # 大恒新相机MER2-231-41U3C裁剪参数
    xmin, ymin, w, h = 500, 200, 800, 600
    frame = frame[ymin:ymin + h, xmin:xmin + w]

    # 根据油菜照片的杂质成分阈值设定杂质掩码
    lower_img = np.array([45, 50, 52])
    upper_img = np.array([155, 185, 200])
    # mask -> 1 channel
    mask0 = cv2.inRange(frame, lower_img, upper_img)
    # Copy the thresholded image.
    im_floodfill = mask0.copy()
    # 执行漫水填充方法
    # Mask 用于 floodFill，官方要求长宽+2
    h, w = mask0.shape[:2]
    mask = np.zeros((h + 2, w + 2), np.uint8)
    # 漫水填充从(0,0)点开始
    # floodFill函数中的seedPoint对应像素必须是背景
    cv2.floodFill(im_floodfill, mask, (0, 0), 255)
    # 得到im_floodfill 255填充非孔洞值
    # cv2.imshow("floodfilled0", im_floodfill)
    # 漫水填充图像取反
    im_floodfill_inv = cv2.bitwise_not(im_floodfill)
    # cv2.imshow("floodfilledimage", im_floodfill_inv)
    # 取反图像与二值图求并集，完成孔洞填充
    im_out = mask0 | im_floodfill_inv
    # 轮廓检测
    contours, hierarchy = cv2.findContours(im_out, cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE)
    copy2 = frame.copy()
    conts = []
    pix = 0
    for x in contours:
        area = cv2.contourArea(x)
        if area > 150:
            conts.append(x)
            cv2.drawContours(copy2, conts, -1, (255, 0, 0), 2)
            pix = pix + area

    m, n = copy2.shape[:2]
    hanzaPix = pix / (m * n) * 100
    hanzaReal = hanzaPix / 8
    # str0 = "percent of zazhi found via contour detection is {:.2f}%.".format(hanza)
    current_time = time.strftime("%Y-%m-%d-%H-%M-%S")
    # detection_result = current_time + ":" + "\t" + "{:.2f}%".format(hanzaReal)

    # 显示原始图像和处理后的图像
    # cv2.namedWindow('original', cv2.WINDOW_NORMAL)  # 创建一个名为video的窗口
    # cv2.resizeWindow('original', 969, 723)
    # cv2.imshow('original', frame)
    cv2.namedWindow('result', cv2.WINDOW_NORMAL)  # 创建一个名为video的窗口
    cv2.resizeWindow('result', 969, 723)
    cv2.imshow('result', copy2)
    # with open('D:/Python/myworkspace/results.txt', 'a') as f:
    #     f.write(detection_result + '\n')

    if current_time == time0:
        imgname = current_time + '(' + str(tttt) + ')'
        detection_result = imgname + ":" + "\t" + "{:.2f}%".format(hanzaPix) + "\t" + "{:.2f}%".format(hanzaReal)
        with open('D:/Python/myworkspace/results.txt', 'a') as f:
            f.write(detection_result + '\n')
        # cv2.imwrite('D:/Python/myworkspace/imagesave/' + imgname + '.jpg', frame)
        tttt = tttt + 1
    else:
        detection_result = current_time + ":" + "\t" + "{:.2f}%".format(hanzaPix) + "\t" + "{:.2f}%".format(hanzaReal)
        with open('D:/Python/myworkspace/results.txt', 'a') as f:
            f.write(detection_result + '\n')
        # cv2.imwrite('D:/Python/myworkspace/imagesave/' + current_time + '.jpg', frame)
        tttt = 1

    time0 = current_time

    if cv2.waitKey(1) & 0xFF == 27 or cv2.getWindowProperty('result', cv2.WND_PROP_VISIBLE) < 1.0 \
            or cv2.getWindowProperty('result', cv2.WND_PROP_VISIBLE) < 1.0:
        break

# 释放摄像头并关闭所有窗口
cam.stream_off()
# close device
cam.close_device()
cv2.destroyAllWindows()

